package com.sky.service.impl;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        List<LocalDate> dateList = getDateList(begin, end);
        //营业额，以逗号分隔，例如：406.0,1520.0,75.0
        //需要和日期列表对应 根据日期和订单状态查询 返回订单总金额
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //在beginTime和endTime之间 同时满足订单状态为完成 的订单
            //SELECT SUM(amount) FROM orders WHERE order_time BETWEEN beginTime AND endTime AND status = ?
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        //用户总量，以逗号分隔，例如：200,210,220 根据createTime < end
        List<Integer> totalUserList = new ArrayList<>();
        //新增用户，以逗号分隔，例如：20,21,10 根据 end > createTime > begin
        List<Integer> newUserList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end",endTime);
            totalUserList.add(userMapper.countByMap(map));
            map.put("begin",beginTime);
            newUserList.add(userMapper.countByMap(map));
        });
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        //每日订单数，以逗号分隔，例如：260,210,215 根据 begin <createTime < end
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数，以逗号分隔，例如：20,21,10 订单状态是已完成的 根据 begin < createTime < end
        List<Integer> validOrderCountList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer orderCount = orderMapper.countByMap(map);
            orderCount = orderCount == null ? 0 : orderCount;
            orderCountList.add(orderCount);
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;
            validOrderCountList.add(validOrderCount);
        });
        //订单总数 orderCountList stream流求和
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数 validOrderCountList stream流求和
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率 = 有效订单数 / 总订单数 * 100%
        Double orderCompletionRate = 0.0;

        if (totalOrderCount != 0 && totalOrderCount > 0) {
            // 转为 double 避免整数除法
            double valid = validOrderCount != 0 ? validOrderCount.doubleValue() : 0.0;
            double total = totalOrderCount.doubleValue();
            orderCompletionRate = (valid / total);
        } else {
            // 总订单数为 0，完成率定义为 0%（或 NaN，但通常业务上设为 0）
            orderCompletionRate = 0.0;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(map);
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
/**
 * 导出业务数据的方法
 * @param response HTTP响应对象，用于将导出的数据写入响应流中
 * 该方法用于将业务数据导出为文件，并通过HTTP响应对象返回给客户端
 */
    public void exportBusinessData(HttpServletResponse response) {
        //1,查询营业数据
        //30天的数据
        LocalDate beginDay = LocalDate.now().minusDays(30);
        LocalDate endDay = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(beginDay, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(endDay, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
            //2,通过poi 将数据写入excel模板
            //创建输入流
            try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx")) {
                XSSFWorkbook excel = new XSSFWorkbook(inputStream);
                XSSFSheet sheet = excel.getSheetAt(0);
                //概览数据
                sheet.getRow(1).getCell(1).setCellValue(beginDay + "至" + endDay);
                sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
                sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
                //明细数据
                List<LocalDate> dateList = getDateList(beginDay, endDay);
                final int[] rowNum = {7};
                dateList.forEach(date -> {
                    LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
                    LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
                    BusinessDataVO data = workspaceService.getBusinessData(beginTime, endTime);
                    sheet.getRow(rowNum[0]).getCell(1).setCellValue(String.valueOf(date));
                    sheet.getRow(rowNum[0]).getCell(2).setCellValue(data.getTurnover());
                    sheet.getRow(rowNum[0]).getCell(3).setCellValue(data.getValidOrderCount());
                    sheet.getRow(rowNum[0]).getCell(4).setCellValue(data.getOrderCompletionRate());
                    sheet.getRow(rowNum[0]).getCell(5).setCellValue(data.getUnitPrice());
                    sheet.getRow(rowNum[0]).getCell(6).setCellValue(data.getNewUsers());
                    rowNum[0]++;
                });
                //3,将excel文件输出到浏览器
                ServletOutputStream outputStream = response.getOutputStream();
                excel.write(outputStream);
                outputStream.close();
                excel.close();
            }catch (IOException e){
                log.error("导出Excel失败");
            }
    }

    private List<LocalDate> getDateList(LocalDate begin,LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
